'use strict'

import { app, shell, dialog, BrowserWindow, Tray, Menu, globalShortcut, ipcMain } from 'electron'
import store from '../renderer/store/modules/Config'
import StreamDownload from './download'
console.log(StreamDownload)
const os = require('os')
const fs = require('fs')
const path = require('path')
var config = require('../../package.json')
console.log(os.arch())
console.log(os.release())
/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

const mainURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`
const loginURL = mainURL + '#/login'
const noticeURL = mainURL + '#/notice'
var tray
setInterval(() => {
  console.log(tray)
}, 5000)
/**
 * 递归删除非空文件夹
 */
function deleteFolderRecursive (dir) {
  if (fs.existsSync(dir)) {
    fs.readdirSync(dir).forEach(function (file) {
      var curPath = dir + '/' + file
      if (!fs.statSync(curPath).isDirectory()) { // recurse
        fs.unlinkSync(curPath)
      } else {
        deleteFolderRecursive(curPath)
      }
    })
    fs.rmdirSync(dir)
  }
}
let mainWindow
/**
 * 创建主窗口
 */
function createMain () {
  mainWindow = new BrowserWindow({
    width: process.env.NODE_ENV === 'development' ? 860 + 294 : 860,
    height: 530,
    minWidth: 860,
    minHeight: 530,
    frame: false,
    transparent: true,
    webPreferences: {
      webSecurity: false
    }
  })
  mainWindow.loadURL(mainURL)
  // let hwnd = mainWindow.getNativeWindowHandle()
  // console.log(hwnd)
  // user32.GetSystemMenu(hwnd.readUInt32LE(0), true)
  // console.log('success used User32')
  mainWindow.hookWindowMessage(278, function (e) {
    mainWindow.setEnabled(false)
    setTimeout(function () {
      mainWindow.setEnabled(true)
    }, 100)
  })
  mainWindow.on('closed', () => { mainWindow = null })
  mainWindow.on('focus', () => {
    mainWindow.flashFrame(false)
  })
}
let loginWindow
/**
 * 创建登录窗口
 */
function createLogin () {
  loginWindow = new BrowserWindow({
    width: process.env.NODE_ENV === 'development' ? 333 + 400 : 333,
    height: 423,
    minWidth: 333,
    minHeight: 423,
    resizable: false,
    frame: false,
    transparent: true
  })
  loginWindow.loadURL(loginURL)
  loginWindow.hookWindowMessage(278, function (e) {
    loginWindow.setEnabled(false)
    setTimeout(function () {
      loginWindow.setEnabled(true)
    }, 100)
  })
  loginWindow.on('closed', () => { loginWindow = null })
}
let noticeWindow
/**
 * 创建通知窗口
 */
function createNotice () {
  noticeWindow = new BrowserWindow({
    kiosk: true,
    alwaysOnTop: true,
    skipTaskbar: true,
    frame: false,
    transparent: true,
    show: false
  })
  noticeWindow.loadURL(noticeURL)
  noticeWindow.hookWindowMessage(278, function (e) {
    noticeWindow.setEnabled(false)
    setTimeout(function () {
      noticeWindow.setEnabled(true)
    }, 100)
  })
  noticeWindow.on('closed', () => { noticeWindow = null })
}
const trayContextMenu = Menu.buildFromTemplate([
  {
    label: '  打开窗口  ',
    click: () => {
      if (mainWindow) {
        mainWindow.setOpacity(0)
        mainWindow.show()
        setTimeout(function () {
          mainWindow.setOpacity(1)
        }, 100)
      }
    }
  }, {
    label: '  清除数据  ',
    click: () => {
      var dbpath = path.join(app.getPath('userData'), 'data', store.state.serviceType)
      deleteFolderRecursive(dbpath)
    }
  }, {
    label: '  开发者工具  ',
    submenu: [
      {
        label: '主界面',
        click: () => {
          mainWindow.webContents.openDevTools({
            mode: 'detach'
          })
        }
      },
      {
        label: '通知界面',
        click: () => {
          noticeWindow.webContents.openDevTools({
            mode: 'detach'
          })
        }
      },
      {
        label: '登录界面',
        click: () => {
          loginWindow.webContents.openDevTools({
            mode: 'detach'
          })
        }
      }
    ]
  }, {
    label: '  退出海草  ',
    click: () => {
      if (mainWindow) mainWindow.destroy()
      if (noticeWindow) noticeWindow.destroy()
      if (loginWindow) loginWindow.destroy()
      app.exit()
    }
  }
])
/**
 * 创建任务栏图标
 */
function createTray () {
  tray = null
  tray = new Tray(__static + '/icon_show.ico') // 创建任务栏图标
  // 右键任务栏图标
  tray.on('right-click', () => {
    // 弹出菜单
    tray.popUpContextMenu(trayContextMenu)
  })
  // 图标文字提示
  tray.setToolTip(`海草客服\nV${config.version}_${store.state.serviceType}`)
  // 图标点击事件
  tray.on('click', () => { // 图标点击事件
    if (mainWindow) {
      mainWindow.setOpacity(0)
      mainWindow.show()
      setTimeout(function () {
        mainWindow.setOpacity(1)
      }, 100)
    }
  })
}

app.on('ready', () => {
  createMain() // 创建主窗口
  createTray() // 创建任务栏图标
  createNotice() // 创建通知窗口
  globalShortcut.register('CommandOrControl+Alt+Shift+P', () => { // 打开调试窗口
    createTray()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createMain()
  }
})
// 主窗口最小化
ipcMain.on('main_min', function (event, data) {
  if (mainWindow) mainWindow.minimize()
})
// 主窗口最大化
let isMaximizeds = 0
ipcMain.on('main_max', function (event, data) {
  if (isMaximizeds) {
    mainWindow.unmaximize()
    isMaximizeds = 0
  } else {
    mainWindow.maximize()
    isMaximizeds = 1
  }
})
// 主窗口隐藏
ipcMain.on('main_hide', function (event, data) {
  if (mainWindow) mainWindow.hide()
})

// 主窗口活动
ipcMain.on('main_flash_frame', function () {
  if (mainWindow) {
    if (!mainWindow.isFocused()) {
      mainWindow.flashFrame(true)
    }
  }
})

// 主窗口显示
ipcMain.on('main_show', function (event, data) {
  if (mainWindow) {
    mainWindow.setOpacity(0)
    mainWindow.show()
    setTimeout(function () {
      mainWindow.setOpacity(1)
    }, 100)
    mainWindow.webContents.send('notice_to_msg', data)
  }
})

// 通知窗口显示
ipcMain.on('main_click_userchat', function (event, data) {
  if (!noticeWindow) createNotice()
  noticeWindow.webContents.send('main_click_userchat', data)
})
// 通知窗口显示
ipcMain.on('notice_show', function (event, data) {
  if (!noticeWindow) createNotice()
  noticeWindow.showInactive()
  noticeWindow.webContents.send('new_msg', data)
})
// 通知窗口隐藏
ipcMain.on('notice_hide', function (event, data) {
  if (noticeWindow) noticeWindow.hide()
})

// 通知窗口隐藏
ipcMain.on('login_hide', function (event, data) {
  if (loginWindow) loginWindow.close()
})
// 通知窗口显示
ipcMain.on('login_show', function (event, data) {
  if (!loginWindow) createLogin()
  loginWindow.show()
})

// 登录请求成功
// 1.发送状态给 主窗口开始加载资源
ipcMain.on('login_success', function (event, data) {
  if (!mainWindow) createMain()
  mainWindow.webContents.send('login_success', data)
})

// 登录加载资源出错
ipcMain.on('load_res_error', function (event, data) {
  loginWindow.webContents.send('load_res_error')
})

// 登录加载资源成功
ipcMain.on('load_res_success', function (event, data) {
  console.log('loading success')
  if (loginWindow) loginWindow.close()
  mainWindow.show()
})

// 创建群发任务
ipcMain.on('send_mass_msg', function (event, data) {
  mainWindow.webContents.send('send_mass_msg', data)
})
// 下载新版本安装包
ipcMain.on('download_install1', function (event, data) {
  var downloadUrl = data.url
  var downloadDir = data.dir
  var fileName = require('path').basename(downloadUrl)
  const options = {
    type: 'info',
    title: '下载完成',
    message: '安装包下载完成，是否立即更新！',
    buttons: ['是', '否']
  }
  require('fs').readFile(require('path').join(downloadDir, fileName), function (err, res) {
    if (err) {
      deleteFolderRecursive(downloadUrl)
      StreamDownload.downloadFile(downloadUrl, downloadDir, function (arg, percentage) {
        console.log(arg, percentage)
        if (arg === 'finished') {
          dialog.showMessageBox(options, (index) => {
            if (index === 0) {
              shell.openExternal(require('path').join(downloadDir, fileName))
            }
          })
        }
      })
    } else {
      console.log('文件已存在提示用户打开安装！')
      dialog.showMessageBox(options, (index) => {
        console.log(options.buttons[index])
        if (index === 0) {
          shell.openExternal(require('path').join(downloadDir, fileName))
        }
      })
    }
  })
})
